<template>
  <a-form-item-rest>
    <a-input-number v-bind:="$attrs" :max="startMax" v-model:value="startValue" @change="changeValue" @focus="focusHandle" @blur="blurHandle" />
    {{separator}}
    <a-input-number v-bind:="$attrs" :min="endMin" v-model:value="endValue" @change="changeValue" @blur="blurEndHandle" />
  </a-form-item-rest>
</template>

<script>
export default {
  name: "ExNumberRange"
}
</script>
<script setup>
import {ref, computed, watch, useAttrs} from "vue";
import {Form} from "ant-design-vue";
const attrs = useAttrs()
const emit = defineEmits(['update:value','update:startValue','update:endValue'])
const props = defineProps({
  value:{
    type:Array,
    default:[],
  },
  startField:String,
  endField:String,
  startValue:Number,
  endValue:Number,
  separator:{
    type:String,
    default:'-',
  }
})
const startValue = ref(props.startValue)
const endValue = ref(props.endValue)
initValue()

const formItemContext = Form.useInjectFormItemContext();
watch(() => props.value, (value,oldValue) => {
  if(JSON.stringify(value) != JSON.stringify(oldValue)){
    initValue()
  }
  if(props.startField === props.endField){
    emitUpdate(value,value)
  }else{
    emitUpdate(value[0],value[1])
  }
  formItemContext.onFieldChange()
})
function initValue(){
  if(props.value.length > 0){
    startValue.value  = props.value[0]
    endValue.value  = props.value[1]
  }else{
    startValue.value = null
    endValue.value = null
  }
  changeValue()
}
function changeValue(){
  if((startValue.value === null || startValue.value === undefined) && (endValue.value === null || endValue.value === undefined)){
    emit('update:value',[])
  }else{
    emit('update:value',[startValue.value,endValue.value])
  }
}
function emitUpdate(start,end){
  emit('update:startValue', start)
  emit('update:endValue', end)
}
let clearStart = false
function focusHandle(){
  clearStart = false
}
function blurHandle(e){
  if(startValue.value === null){
    endValue.value = null
  }
  setTimeout(()=>{
    if(startValue.value !== null && !endValue.value){
      endValue.value = endDefaultValue()
    }
    if(startValue.value !== null && startValue.value === endValue.value){
      endValue.value = endDefaultValue()
    }
    changeValue()
  },500)
}
function blurEndHandle(){
  clearStart = true
  if(startValue.value === null && endValue.value !== null){
    startValue.value = startDefaultValue()
  }
  setTimeout(()=>{
    if(endValue.value === null && clearStart){
      startValue.value = null
    }
    changeValue()
  },300)
}
function endDefaultValue(){
  const step = attrs.step || 1
  return startValue.value + step
}
function startDefaultValue(){
  const step = attrs.step || 1
  return endValue.value - step
}
const endMin = computed(()=>{
  return endDefaultValue()
})
const startMax = computed(()=>{
  if(attrs.max){
    const step = attrs.step || 1
    return attrs.max - step
  }
  return null
})
</script>
<style scoped>

</style>
